<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    {{studentForm}}
    <el-form :model="studentForm" :rules="rules" ref="ruleForm">
      <el-form-item label="学生姓名" :label-width="formLabelWidth" prop="sname">
        <el-input v-model="studentForm.sname" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="学生性别" :label-width="formLabelWidth"  prop="sex">
        <el-select v-model="studentForm.sex" placeholder="选择性别"  style="width:100%">
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学生年龄" :label-width="formLabelWidth" prop="age">
        <el-input v-model.number="studentForm.age" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="学生住址" :label-width="formLabelWidth" prop="addr">
        <el-input v-model="studentForm.addr" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="所在班级" :label-width="formLabelWidth" prop="cid">
        <el-select v-model="studentForm.cid"   style="width:100%">
          <el-option :label="c.cname" :value="c.cid" v-for="(c,index) in classes" :key="index"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { save,findById} from "@/api/student";
  import {findClasses} from "@/api/classes";

  export default {
    name: "add-or-update",
    data(){
      //1. 定义校验年龄的自定义规则
      const checkAge = (rule, value, callback) => {
        if (!value) {
          callback(new Error('年龄不能为空！'));
        } else {
          if (!Number.isInteger(value)) {
            callback(new Error('年龄必须是整数!'));
          }
          callback();
        }
      };
      return {
        title:'添加学生',
        formLabelWidth:'120px',
        dialogFormVisible:false,
        studentForm:{},
        classes:[],
        rules:{
          sname:[
            { required: true, message: '请输入学生姓名', trigger: 'blur' },
          ],
          sex:[
            { required: true, message: '请选择性别', trigger: 'change' },
          ],
          age:[
            // { required: true, message: '请输入学生年龄', trigger: 'blur' },
            { trigger:'blur',validator:checkAge }
          ],
          addr:[
            { required: true, message: '请输入学生住址', trigger: 'blur' },
          ],
          cid:[
            { required: true, message: '请选择班级', trigger: 'change' },
          ]
        }
      }
    },
    created() {
      //3. 查询所有班级
      this.findClasses();
    },
    methods:{

      //3. 查询所有班级
      findClasses(){
        findClasses().then(({data})=>{
          this.classes = data.classes;
        })
      },
      //4. 子组件的初始化方法
      init(stud){
        this.dialogFormVisible = true;
        this.studentForm = stud;
      },
      //5. 保存学生
      save(){
        //5.1 如果表单中的所有控件都验证通过，其返回的回调参数valid就为true,此时，可以向后台发请求，否则，返回 的是false
        this.$refs.ruleForm.validate(valid=>{
          let _this = this;
          if(valid){  // 如果表单的所有控件都验证通过，就提交到后台
            let url = "/student/add";   //添加的url地址
            //5.2 根据studentForm.sid是否有值决定，是添加还是修改操作
            if(this.studentForm.sid){
              url = "/student/update";
            }
            //5.3 向后台发送请求
            save(url,this.studentForm).then((data)=>{
              console.log(data)
              //5.3.1 如果添加成功
              if(data.code == 20000) {
                this.$message({
                  showClose: true,
                  message: `恭喜你，${this.studentForm.sid?'修改':'添加'}学生成功！`,
                  type: 'success',
                  onClose(){    // 消息框关闭后，自动回调此函数
                    //① 刷新学生列表(向父组件传递事件,并执行父组件的事件)
                    _this.$emit('refreshDataList')
                    //② 关闭对话框
                    _this.dialogFormVisible = false;
                  }
                });
              }
            })
          }
        })
      },
      //6. 修改学生（界面）
      handleEdit(index, row) {
        console.log(index, row);
        //6.1 为studentForm对象赋值
        this.studentForm = row;
        //6.2 修改标题
        this.title = "修改学生";
        //6.3 显示对话框
        this.dialogFormVisible = true;
      },

    }
  }
</script>

<style scoped>

</style>
